package com.example.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.edu.client.VodClient;
import com.example.edu.entity.Video;
import com.example.edu.mapper.VideoMapper;
import com.example.edu.service.VideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author 李泽伟
 * @since 2022-05-28
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Resource
    VodClient vodClient;

    //1 根据课程id删除小节，删除对应视频文件
    @Override
    public void removeVideoByCourseId(String courseId) {
        //1.通过课程id查询所有小节
        QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",courseId);
        queryWrapper.select("video_source_id");
        List<Video> videos = baseMapper.selectList(queryWrapper);
        //2.封装所有小节的视频id List<Video>---->List<String>
        List<String> ids=new ArrayList<>();
        for (Video video : videos) {
            String videoSourceId = video.getVideoSourceId();
            if(!StringUtils.isEmpty(videoSourceId)){
                ids.add(videoSourceId);
            }
        }
        //3.调用vod服务删除所有视频
        if (ids.size() >0) {
            vodClient.deleteBatch(ids);
        }
        //4.删除所有小节
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        baseMapper.delete(wrapper);
    }
}
